<?php
/**
 * Zend Framework
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://framework.zend.com/license/new-bsd
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@zend.com so we can send you a copy immediately.
 *
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage Zend_Controller_Action_Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @version    $Id$
 */
/** Zend_Controller_Action_Helper_Abstract */
require_once 'Zend/Controller/Action/Helper/Abstract.php';
require_once 'Core/User.php';

/**
 * Helper for interacting with Zend_Controller_Plugin_Acl
 *
 * @uses       Zend_Controller_Action_Helper_Abstract
 * @category   Zend
 * @package    Zend_Controller
 * @subpackage Zend_Controller_Action_Helper
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Core_Controller_Action_Helper_Acl extends Zend_Controller_Action_Helper_Abstract
{
	/**
	 * The default role name.
	 * 
	 * @var string
	 */
	const DEFAULT_ROLE_NAME = 'default';

	/**
	 * @var Zend_Acl
	 **/
	protected $_acl;

	/**
	 * Constructor
	 *
	 * @return void
	 */
	function __construct ()
	{
		// Retrieve the ACL from the application bootstrap
		$this->_acl = $this->getFrontController()
			->getDispatcher()
			->getParam('bootstrap')
			->getResource('acl');
	}

	/**
	 * Pulls common stored data to enforce a specific resource.
	 * 
	 * @param string $resource
	 * @param string $privilege
	 * @param uint $http_error_code
	 */
	public function requireResource ($resource = null, $privilege = null, $http_error_code = 403)
	{
		// Are we logged in?
		if (Zend_Auth::getInstance()->hasIdentity())
		{
			// We have an identity- let's see if we have a user.
			$user = Core_User::getCurrentUser();
			if ($user == null || ! $this->_acl->isAllowed($user->role, $resource, $privilege))
			{
				throw new Zend_Controller_Action_Exception('Access Denied', $http_error_code);
			}
		}
		else
		{
			// We are not logged in. Check acl with default user role.
			if ($this->_acl->hasRole(Core_User::ROLE_GUEST) && $this->_acl->isAllowed(Core_User::ROLE_GUEST, $resource, $privilege))
			{
				// Looks like it works!
				return;
			}
			else
			{
				throw new Zend_Controller_Action_Exception('Access Denied', $http_error_code);
			}
		}
	}
}